﻿using BaseNet.Core.Dtos;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace BaseNet.Core.Utils
{
    /// <summary>
    /// 枚举转集合
    /// </summary>
    public class EnumHelper
    {
        /// <summary>
        /// 枚举转SelectItemDto
        /// </summary>
        /// <typeparam name="TEnum"></typeparam>
        /// <returns></returns>
        public static List<SelectItemDto> EnumToList<TEnum>()
        {
            List<SelectItemDto> list = new List<SelectItemDto>();

            foreach (var item in Enum.GetValues(typeof(TEnum)))
            {
                var listItem = new SelectItemDto()
                {
                    Value = ((int)item).ToString(),
                    Text = item.ToString()
                };
                list.Add(listItem);
            }
            list = list.OrderBy(o => Convert.ToInt32(o.Value)).ToList();
            return list;
        }
        /// <summary>
        /// 枚举转SelectItemDto(text为Description说明)
        /// </summary>
        /// <typeparam name="TEnum"></typeparam>
        /// <returns></returns>
        public static List<SelectItemDto> EnumToListByDescription<TEnum>()
        {
            List<SelectItemDto> list = new List<SelectItemDto>();
            foreach (var item in Enum.GetValues(typeof(TEnum)))
            {
                var listItem = new SelectItemDto()
                {
                    Value = ((int)item).ToString(),
                    Text = GetDescription((Enum)item)
                };
                list.Add(listItem);
            }
            return list;
        }

        /// <summary>
        /// 获取枚举说明
        /// </summary>
        /// <param name="en"></param>
        /// <returns></returns>
        public static string GetDescription(Enum en)
        {
            Type type = en.GetType();   //获取类型  
            MemberInfo[] memberInfos = type.GetMember(en.ToString());   //获取成员  
            if (memberInfos != null && memberInfos.Length > 0)
            {
                DescriptionAttribute[] attrs = memberInfos[0].GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];   //获取描述特性  
                if (attrs != null && attrs.Length > 0)
                {
                    return attrs[0].Description;    //返回当前描述
                }
            }
            return en.ToString();
        }
    }
}
